import axios from 'axios';
import {DataUtils} from '../util/data_utils';
import {ECDSAUtils} from '../util/ecdsa_util';
import {UUID} from '../util/UUIDUtil';
import {ApplyAccessTokens} from './api';

export const baseURL = 'http://106.52.116.247:13046/api/';
export const keyId = 'beanBag';

const axiosOption = {
  baseURL: baseURL,
  timeout: 15000,
};

// 替换以下token，过期需更换
const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MzMzNzAwNjUsImFwcElkIjoiYmVhbkJhZyIsInVzZXJJZCI6ImdyYXlzb256aGFuZyIsIm5vbmNlIjoxNzMyNTA2MDY1MTI3LCJhZG1pbiI6dHJ1ZX0.-pTt-l0oODEsBbDbPv-lFPh1RKNlq-N2UuIAvSLmeSI';  
let alertTokenValid = false;
const userId = 'graysonzhang';

const service = axios.create(axiosOption);
console.log('baseURL:', baseURL);

service.interceptors.request.use(
  async config => {
    // console.log('config.url = ', config.url);
    if (config.url === '/account/saveMnemonicInfo') {
      config.baseURL = "http://172.21.13.13:43931/api";
      return config;
    } else{
      config.baseURL = baseURL;
    }

    if (userId) {
      config.headers.userId = userId;
      config.headers.appId = keyId;
    }
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    } else {
      // console.log('get token from asyn redux failed');
    }
    // console.log('config headers : ', config.headers);
    return config;
  },
  error => {
    // console.log('request error is', error);
    return Promise.reject(error);
  },
);

service.interceptors.response.use(
  response => {
    return response.data;
  },
  async error => {
    // 处理 HTTP 错误
    if (error.response) {
      // console.log(
      //   `请求失败: ${error.response.status} ${error.response.statusText}`,
      // );
      if (error.response.status === 401 || error.response.status === 403) {
        if (!alertTokenValid) {
          alertTokenValid = true;
        }

        return error.response;
      }
      if (error.response.status === 503) {
        return {data: ''};
      }
    }
    return Promise.reject(error);
  },
);


export default service;
